import { BaseContext } from 'koa'
import { getManager, Repository } from 'typeorm'
import { Staticfile } from '../entity/staticfile'

import { OKBody, FailBody } from '../utils/requests/index'
import { shouldBlock } from '../utils/middleware/parseCtxSession'
import * as KoaMulter from 'koa-multer'
import { config } from '../config'
import { saveJSON } from '../utils/saveJson/index'

const diskStorage = KoaMulter.diskStorage({
  destination: `${config.designFileFolder}/${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()}`,
  filename (ctx, file, cb) {
    const fnList = file.originalname.split('.')
    cb(
      undefined,
      // `${Date.now()}-${fnList.slice(fnList.length - 2).join('.')}`,
      `${Date.now()}-${fnList.slice(fnList.length - 2).join('.')}`,
    )
  }
})
const upload = KoaMulter({ storage: diskStorage })

export default class UserController {
  public static async uploadHTML(ctx: BaseContext) {
    // 上传HTML content
    // 保证JSON合格性
    // 生成JSON文件
    // 合并成合法的HTML
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    try {
      const body = ctx.request.body
      if (!body.content) return ctx.body = FailBody('content字段不能为空')

      const jsonStr = body.content

      const filename = await saveJSON(jsonStr)

      ctx.body = OKBody({
        filename: `/json/${filename}`,
        length: jsonStr.length,
      })
    } catch (err) {
      ctx.body = FailBody(err.message)
    }
  }

  public static async onFileUpload(ctx: BaseContext) {
    if (shouldBlock(ctx)) return ctx.body = FailBody(shouldBlock(ctx))

    try {
      const fileInfo = ctx.req.file
      console.log('fileInfo', fileInfo)

      const body = ctx.req.body

      // console.log('body', body)
      const repo: Repository<Staticfile> = getManager().getRepository(Staticfile)

      const session = ctx.session
      const staticFileToSave = new Staticfile()

      staticFileToSave.createdTime = new Date()
      // 注意路径
      staticFileToSave.url = fileInfo.path.replace(/.+?img\//, '/')
      staticFileToSave.userid = session.userid
      staticFileToSave.userNickname = session.nickname
      staticFileToSave.mimetype = fileInfo.mimetype
      staticFileToSave.size = fileInfo.size
      staticFileToSave.originalname = fileInfo.originalname
      staticFileToSave.projectId = body.projectId

      // 保存文件信息
      console.log('staticFileToSave: ', staticFileToSave)
      await repo.save(staticFileToSave)

      ctx.body = OKBody(
        {
          originalname: fileInfo.originalname,
          url: fileInfo.path.replace(/.+?\/public\//, '/'),
          projectId: body.projectId,
        },
        200,
        '上传成功',
      )
    } catch (err) {
      console.log(err)
      ctx.body = FailBody(err.message)
    }
  }

  public static getUploadConfig(configStr: string = 'file') {
    return upload.single(configStr)
  }
}
